package com.ciwong.epaper.modules.me.ui;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.dbbean.AnswerContent;
import com.ciwong.epaper.modules.dbbean.LswAnswer;

import com.ciwong.epaper.modules.epaper.bean.RecordSubmitPart;
import com.ciwong.epaper.modules.epaper.dao.LswDao;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.ui.RereadWordResultActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * Created by young on 2017/10/17.
 * 测试网络环境页面  听说模考上传  单词句子上传   作业下载
 */

public class NetTestActivity extends BaseActivity implements View.OnClickListener {
    private TextView read_tv, speak_tv, down_tv, net_name_tv, phone_type_tv, os_tv, ver_tv;
    private Button net_btn;

    private String path;
    private long timer;
    private boolean isRetry = true, read_b = false, speak_b = false, down_b = false;
    private final int TIME_OUT = 10000;//计时器
    private int submint_timer = 0;
    private BaseDownloadTask task;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case TIME_OUT:
                    submint_timer++;
                    if (submint_timer < 30) {
                        mHandler.sendEmptyMessageDelayed(TIME_OUT, 1000);
                    } else {
                        if (!read_b) {
                            read_b = true;
                            read_tv.setText("请求超时");
                        }
                        if (!speak_b) {
                            speak_b = true;
                            speak_tv.setText("请求超时");
                        }
                        if (!down_b) {
                            down_b = true;
                            down_tv.setText("请求超时");
                        }
                        if (read_b && speak_b && down_b) {
                            net_btn.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_net_test;
    }

    @Override
    protected void findViews() {
        read_tv = (TextView) findViewById(R.id.read_tv);
        speak_tv = (TextView) findViewById(R.id.speak_tv);
        down_tv = (TextView) findViewById(R.id.down_tv);
        net_name_tv = (TextView) findViewById(R.id.net_name_tv);
        phone_type_tv = (TextView) findViewById(R.id.phone_type_tv);
        os_tv = (TextView) findViewById(R.id.os_tv);
        ver_tv = (TextView) findViewById(R.id.ver_tv);
        net_btn = (Button) findViewById(R.id.net_btn);
    }

    @Override
    protected void preCreate() {
        super.preCreate();
//        setNeedCheck(true);
    }

    @Override
    protected void initEvent() {
        net_btn.setOnClickListener(this);
    }

    @Override
    protected void init() {
        ALiYunManager.getInstance().registerListener(aLIyunlistener);
        setTitleText("网络测速");
    }

    @Override
    protected void loadData() {
        if (isRetry) {
            testNet();
        }

    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.net_btn) {
            if (isRetry) {
                testNet();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ALiYunManager.getInstance().unRegisterListener(aLIyunlistener);
    }


    public void testNet() {
        try {
            submint_timer = 0;//计时归0
            mHandler.sendEmptyMessage(TIME_OUT);//发动计时器
            net_btn.setVisibility(View.GONE);
            read_b = false;
            speak_b = false;
            down_b = false;
            if (NetworkUtils.isOnline()) {
                String targetPath = ESystem.getProjectFolderPath(NetTestActivity.this)
                        + File.separator + ESystem.TEST + ".mp3";
                path = targetPath;
                timer = System.currentTimeMillis();
                read_tv.setText("检测中...");
                speak_tv.setText("检测中...");
                down_tv.setText("检测中...");
                net_name_tv.setText("检测中...");
                phone_type_tv.setText("检测中...");
                os_tv.setText("检测中...");
                ver_tv.setText("检测中...");
                if (new File(path).exists()) {
                    ALiYunManager.getInstance().addMP3(path, path, System.currentTimeMillis());//
                    submitspeak(path);
                    downWork();
                    String appVersion = getAppVersionName(NetTestActivity.this);
                    //        手机型号
                    String netType = FeedbackUtil.getInstance().GetNetworkType(NetTestActivity.this);
                    net_name_tv.setText(netType);
                    os_tv.setText("Android" + android.os.Build.VERSION.RELEASE);
                    phone_type_tv.setText(android.os.Build.MODEL);
                    ver_tv.setText(appVersion);
                } else {
                    targetPath = ESystem.getProjectFolderPath(NetTestActivity.this)
                            + File.separator + ESystem.TEST + ".mp3";
                    File targetFile = new File(targetPath);

                    if (targetFile.exists()) {
                        targetFile.delete();
                    }
                    boolean isSuccess = FileUtil.copyFile(NetTestActivity.this, ESystem.TEST + ".mp3", targetFile);
                    if (isSuccess) {
                        testNet();
                    }
                }
            } else {
                read_b = true;
                speak_b = true;
                down_b = true;
                String appVersion = getAppVersionName(NetTestActivity.this);
                read_tv.setText("上传失败");
                speak_tv.setText("上传失败");
                down_tv.setText("下载失败");
                net_name_tv.setText("网络未连接");
                os_tv.setText("Android" + android.os.Build.VERSION.RELEASE);
                phone_type_tv.setText(android.os.Build.MODEL);
                ver_tv.setText(appVersion);
                net_btn.setVisibility(View.VISIBLE);
            }

        } catch (Exception e) {
            e.getStackTrace();
        }


    }

    //获取当前版本号
    private String getAppVersionName(Context context) {
        String versionName = "未知版本";
        try {
            versionName = context.getString(R.string.version, context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    //上传本地MP3文件监听回调
    private ALiYunManager.ALiYunListener aLIyunlistener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            if (tag.toString().equals(path)) {
                read_b = true;
                long speed = (288 * 1000 / (System.currentTimeMillis() - timer));
                read_tv.setText(speed + "kb/s");
                if (read_b && speak_b && down_b) {
                    net_btn.setVisibility(View.VISIBLE);
                    if (mHandler.hasMessages(TIME_OUT)) {
                        mHandler.removeMessages(TIME_OUT);
                    }
                }
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag.toString().equals(path)) {
                read_tv.setText("上传失败");
                read_b = true;
                if (read_b && speak_b && down_b) {
                    net_btn.setVisibility(View.VISIBLE);
                    if (mHandler.hasMessages(TIME_OUT)) {
                        mHandler.removeMessages(TIME_OUT);
                    }
                }
            }

        }
    };

    public void submitspeak(String path) {//提交听说模考音频
        LswAnswer lswAnswer = new LswAnswer();
        lswAnswer.setWorkSaveUUid(UUID.randomUUID().toString());
        lswAnswer.setRefScore(100);
        lswAnswer.setVersionId("925645624554");
        List<AnswerContent> answerContents = new ArrayList<AnswerContent>();
        AnswerContent answerContent = new AnswerContent();
        answerContent.setContent(path);
        answerContents.add(answerContent);
        lswAnswer.setAnswerContents(answerContents);
        lswAnswer.setAnswerType(5);
        LswDao.getInstance().submitMakeScore(lswAnswer, false, new BaseExtCallBack(NetTestActivity.this, String.valueOf(getUserInfoBase().getUserId())) {
            @Override
            public void success(Object data) {

                long speed = (288 * 1000 / (System.currentTimeMillis() - timer));
                speak_tv.setText(speed + "kb/s");
                speak_b = true;
                if (read_b && speak_b && down_b) {
                    net_btn.setVisibility(View.VISIBLE);
                    if (mHandler.hasMessages(TIME_OUT)) {
                        mHandler.removeMessages(TIME_OUT);
                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                failed(data);
            }

            @Override
            public void failed(Object data) {
                speak_tv.setText("上传失败");
                speak_b = true;
                if (read_b && speak_b && down_b) {
                    net_btn.setVisibility(View.VISIBLE);
                    if (mHandler.hasMessages(TIME_OUT)) {
                        mHandler.removeMessages(TIME_OUT);
                    }
                }
            }
        });
    }


    public void downWork() {//下载测试
        try {
            FileDownloader mFileDownloader = FileDownloader.getImpl();
            mFileDownloader.setMaxNetworkThreadCount(2);
            if (null != task && task.isRunning()) {
                task.cancel();
            }
            task = mFileDownloader.create("https://file.dzb.ciwong.com/epaper/20171004165822/catalogue_6803_1081604_v1507107502.res")
                    .setPath(ESystem.getProjectFolderPath(NetTestActivity.this)
                            + File.separator + "test.zip")
                    .setAutoRetryTimes(1)
                    .setTag("test" + System.currentTimeMillis())
                    .setForceReDownload(true)
                    .setListener(fileDownloadListener);
            task.start();
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    FileDownloadListener fileDownloadListener = new FileDownloadListener() {

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_penging");
        }


        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            CWLog.d("down", "down_connected");
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            try {
                down_b = true;
                if (read_b && speak_b && down_b) {
                    net_btn.setVisibility(View.VISIBLE);
                    if (mHandler.hasMessages(TIME_OUT)) {
                        mHandler.removeMessages(TIME_OUT);
                    }
                }
                long speed = (1 * 1024 * 1000 / (System.currentTimeMillis() - timer));
                if (speed > 1000) {
                    speed = speed / 1000;
                    down_tv.setText(speed + "Mb/s");
                } else {
                    down_tv.setText(speed + "kb/s");
                }
                String filePath = ESystem.getProjectFolderPath(NetTestActivity.this)
                        + File.separator + "test.zip";
                File file = new File(filePath);
                if (file.exists()) {
                    FileUtil.deleteDir(file);
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            down_tv.setText("下载失败");
            down_b = true;
            task.cancel();
            if (read_b && speak_b && down_b) {
                net_btn.setVisibility(View.VISIBLE);
                if (mHandler.hasMessages(TIME_OUT)) {
                    mHandler.removeMessages(TIME_OUT);
                }
            }
        }

        @Override
        protected void warn(BaseDownloadTask task) {
            CWLog.d("down", "down_warn");

        }
    };


}
